package com.example.recyclerviewdemo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
//import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<DemoBean> list;
    private Context context;
    private LayoutInflater layoutInflater;


    public MyAdapter(Context context) {
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    public void setList(List<DemoBean> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = layoutInflater.inflate(R.layout.item, parent,false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        DemoBean demoBean = list.get(position);
        if (demoBean == null) return;
        ViewHolder viewholder = (ViewHolder) holder;
        viewholder.imageView.setImageResource(demoBean.getImgid());
        viewholder.tvtitle.setText(demoBean.getTitle());
        viewholder.tvdes.setText(demoBean.getDescription());
        viewholder.tvdate.setText(demoBean.getTime());
//条目中按钮监听事件
        viewholder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.remove(position);
                notifyDataSetChanged();
            }
        });
//条目点击监听事件
        viewholder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String strid=String.valueOf(list.get(position).getId());
                Toast.makeText(context, strid, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        if(list != null)
            return list.size();

        else return 0;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView tvtitle, tvdes, tvdate;
        Button button;

        public ViewHolder(View itemView) {
            super(itemView);

            imageView = itemView.findViewById(R.id.imageView);
            tvtitle = itemView.findViewById(R.id.textView);
            tvdes = itemView.findViewById(R.id.textView2);
            tvdate = itemView.findViewById(R.id.textView3);
            button = itemView.findViewById(R.id.button);
        }
    }


}
